package com.cj.startup.manager

import com.cj.startup.Startup
import com.cj.startup.StartupResult
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArraySet

object StartupCacheManager {
    //ConcurrentHashMap的Value不能是null，所以用StartupResult包裹一下
    private val mInitializedComponents : ConcurrentHashMap<Class<out Startup<*>>,StartupResult<*>> = ConcurrentHashMap()

    //保存正在执行的任务
    private val mInitializingComponents : CopyOnWriteArraySet<Class<out Startup<*>>> = CopyOnWriteArraySet<Class<out Startup<*>>>()

    //保存任务执行后的结果
    fun saveInitializedComponent(clazz:Class<out Startup<*>>,result:StartupResult<*>){
        mInitializedComponents[clazz] = result
    }

    //检查Startup是否已初始化
    fun hasInitialized(clazz:Class<out Startup<*>>):Boolean = mInitializedComponents.containsKey(clazz)

    //获取Startup执行结果
    /*fun <T> obtainInitializedResult(clazz:Class<out Startup<T>>):StartupResult<T> =
        mInitializedComponents[clazz] as StartupResult<T>*/
    fun obtainInitializedResult(clazz:Class<out Startup<*>>):StartupResult<*>? =
        mInitializedComponents[clazz]

    //保存正在执行的任务
    fun saveInitializingComponent(clazz:Class<out Startup<*>>){
        mInitializingComponents.add(clazz)
    }

    //移除正在执行的任务
    fun removeInitializingComponent(clazz:Class<out Startup<*>>){
        mInitializingComponents.remove(clazz)
    }

    //检查Startup是否正在初始化
    fun hasInitializing(clazz:Class<out Startup<*>>):Boolean = mInitializingComponents.contains(clazz)

    //是否有过初始化
    fun hasInitialize(clazz:Class<out Startup<*>>):Boolean = hasInitialized(clazz) || hasInitializing(clazz)
}